package com.example.farmeri.presenter.base;

import android.content.Intent;
import android.util.Log;

import com.example.farmeri.data.DataParam;
import com.example.farmeri.http.API;
import com.example.farmeri.data.RetrofitManager;
import com.example.farmeri.tools.ResponseUtils;
import com.example.farmeri.ui.farm_manager.FarmManagerActivity;
import com.example.farmeri.ui.login.LoginActivity;

import java.lang.ref.WeakReference;
import java.util.Map;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;

public class BasePresenter<V extends IBaseContract> {
    protected final String TAG = this.getClass().getSimpleName();

    private WeakReference<V> view;

    protected BasePresenter(V v) {
        view = new WeakReference<V>(v);
    }

    protected Retrofit getRetrofit(){
        return RetrofitManager.getManager().getRetrofit();
    }

    protected API getAPI(){
        return RetrofitManager.getManager().getRetrofit().create(API.class);
    }

    protected void showErrorMsg(){
        getView().showMessage("数据请求失败");
    }

    protected V getView(){
        return view.get();
    }

    protected <T> RequestBody createFormBody(Map<String, T> map) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, T> entry : map.entrySet()) {
            builder.add(entry.getKey(),entry.getValue().toString());
        }
        return builder.build();
    }


    protected abstract class SimpleObservable<@NonNull T extends ResponseUtils> implements Observer<T>{

        @Override
        public void onSubscribe(@NonNull Disposable d) {

        }

        @Override
        public void onNext(@NonNull T t) {
            if (t.getCode() == ResponseUtils.CODE_SUCCESS){
                onSuccess(t);
            }else {
                onError(t.getMessage());
            }
        }

        @Override
        public void onError(@NonNull Throwable e) {
            Log.e(TAG, "onError: "+e.getMessage());
            onError("网络连接失败");
        }

        @Override
        public void onComplete() {

        }



        public abstract void onSuccess(@NonNull T t);

        public abstract void onError(String msg);
    }




}
